import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import '../../../models/product.dart';
import '../../../widgets/load_image_widget.dart';
import '../../../services/auth_service.dart';
import '../../../services/order_service.dart';
import '../../../models/order.dart';
import '../../order/logic.dart';

class ProductDetailPage extends StatefulWidget {
  const ProductDetailPage({Key? key}) : super(key: key);

  @override
  State<ProductDetailPage> createState() => _ProductDetailPageState();
}

class _ProductDetailPageState extends State<ProductDetailPage> {
  late Product product;
  final RxInt quantity = 1.obs;
  final AuthService _authService = AuthService();
  final OrderService _orderService = OrderService();

  @override
  void initState() {
    super.initState();
    product = Get.arguments;
  }

  void _incrementQuantity() {
    if (quantity.value < product.stock) {
      quantity.value++;
    } else {
      SmartDialog.showToast('已达到最大库存数量');
    }
  }

  void _decrementQuantity() {
    if (quantity.value > 1) {
      quantity.value--;
    }
  }

  // 刷新订单列表
  void _refreshOrderList() {
    // 获取OrderLogic实例并调用loadOrders方法
    try {
      final orderLogic = Get.find<OrderLogic>();
      orderLogic.loadOrders();
    } catch (e) {
      // 如果OrderLogic实例不存在，则创建一个新的实例
      final orderLogic = Get.put(OrderLogic());
      orderLogic.loadOrders();
    }
  }

  Future<void> _placeOrder() async {
    // 显示加载对话框
    SmartDialog.showLoading(msg: '正在下单...');

    try {
      final userId = await _authService.getCurrentUserId();
      if (userId == null) {
        SmartDialog.dismiss();
        SmartDialog.showToast('用户未登录');
        return;
      }

      final now = DateTime.now();
      final totalAmount = product.price * quantity.value;

      final orderItem = OrderItem(
        orderId: 0, // Will be set after order creation
        productId: product.id!,
        quantity: quantity.value,
        price: product.price,
      );

      final order = Order(
        userId: userId,
        totalAmount: totalAmount,
        status: '待付款',
        orderDate: now.toString(),
        items: [orderItem],
      );

      await _orderService.insertOrder(order);
      SmartDialog.dismiss();
      SmartDialog.showToast('下单成功');

      // 刷新订单列表
      _refreshOrderList();

      // 返回上一页并传递刷新标志
      Get.back(result: true);
    } catch (e) {
      SmartDialog.dismiss();
      SmartDialog.showToast('下单失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('商品详情'),
        backgroundColor: Colors.green,
      ),
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Product image
                  product.imageUrl != null && product.imageUrl!.isNotEmpty
                      ? LoadImageWidget(
                          product.imageUrl!,
                          width: double.infinity,
                          height: 250.h,
                          boxFit: BoxFit.cover,
                        )
                      : Container(
                          width: double.infinity,
                          height: 250.h,
                          color: Colors.grey[300],
                          child: Icon(Icons.image, size: 80, color: Colors.grey),
                        ),
                  // Product info
                  Padding(
                    padding: EdgeInsets.all(16.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '¥${product.price.toStringAsFixed(2)}',
                          style: TextStyle(
                            fontSize: 24.sp,
                            color: Colors.red,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(height: 8.h),
                        Text(
                          product.name,
                          style: TextStyle(
                            fontSize: 20.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(height: 8.h),
                        Text(
                          '库存: ${product.stock}',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Colors.grey[700],
                          ),
                        ),
                        SizedBox(height: 16.h),
                        Text(
                          '商品描述',
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(height: 8.h),
                        Text(
                          product.description,
                          style: TextStyle(
                            fontSize: 14.sp,
                            height: 1.5,
                            color: Colors.black87,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          // Bottom bar with quantity selector and buy button
          Container(
            padding: EdgeInsets.all(16.w),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.black12,
                  blurRadius: 5,
                  offset: Offset(0, -2),
                ),
              ],
            ),
            child: Row(
              children: [
                Text(
                  '数量:',
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(width: 8.w),
                Container(
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey[300]!),
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                  child: Row(
                    children: [
                      InkWell(
                        onTap: _decrementQuantity,
                        child: Container(
                          padding: EdgeInsets.all(8.w),
                          child: Icon(Icons.remove, size: 16.sp),
                        ),
                      ),
                      Container(
                        width: 40.w,
                        alignment: Alignment.center,
                        child: Obx(() => Text(
                              '${quantity.value}',
                              style: TextStyle(fontSize: 16.sp),
                            )),
                      ),
                      InkWell(
                        onTap: _incrementQuantity,
                        child: Container(
                          padding: EdgeInsets.all(8.w),
                          child: Icon(Icons.add, size: 16.sp),
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(width: 16.w),
                Expanded(
                  child: ElevatedButton(
                    onPressed: product.stock > 0 ? _placeOrder : null,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green,
                      padding: EdgeInsets.symmetric(vertical: 12.h),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                    ),
                    child: Text(
                      product.stock > 0 ? '立即购买' : '暂时缺货',
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
